<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];
    
    require_once($rootDir.'/classes/SessionManager.class.php');
    require_once($rootDir.'/classes/db/SQLiteConnector.class.php');
    require_once($rootDir.'/classes/LeproUser.class.php');   
    require_once($rootDir.'/classes/db/LeproUserDAO.class.php');
    require_once($rootDir.'/classes/LeproHelper.class.php');
    require_once($rootDir.'/classes/Card.class.php');
    
    class RResultConstants {
    
        // const ALRDY_REG = 1;
        // const SUCC_SAVE = 2;
        const TIME_ELPS = -2;
    
    }
    
    if (SessionManager::isUserLoggedIn()) {
        $userId = SessionManager::getCurrentUserID();
        if ($userId != null) {
            $connector = SQLiteConnector::getInstance();
            if ($connector->connect()) { // connect to DB
                $userDAO = new LeproUserDAO($connector->getDB()); 
                $user = $userDAO->load($userId); // try to load this user from DB
                $isUserRegistered = ($user != null); // if we've got user - then he is registered
                $cardId = $isUserRegistered ? $user->getCardID() : SessionManager::getVar('cardId');
                $cardScore = Card::getScoreById($cardId, false, null, '2 | ?', '11 | 1');
                $cardCodeFound = LeproHelper::checkUserProfileForCard($userId,
                            Card::getCardSummary($cardId, null, false));
                if ($cardCodeFound === true) { // it can be equal to -1, if error
                    if (SessionManager::isRegistrationRequired() && !$isUserRegistered) {
                        if ((SessionManager::getVar('time') + 60*20) > time()) {
                            SQLiteWMutex::initialize();
                            $newUser = new LeproUser($userId, SessionManager::getVar('uname'));
                            $newUser->setPwdHash(SessionManager::getVar('pwdhash'));
                            $newUser->setEmail(SessionManager::getVar('email'));
                            $newUser->setCardID(SessionManager::getVar('cardId'));
                            $newUser->setTimeRegistered(time());
                            $userDAO->save($newUser);
                            SessionManager::setUserChecked($userId);
                            // echo RResultConstants::SUCC_SAVE;
                            echo $cardScore;
                        } else echo RResultConstants::TIME_ELPS;
                    } else echo $cardScore; 
                    SessionManager::setUserChecked($userId);                   
                } else echo $cardCodeFound; // -1 if not logged, false if no match
            }
        }
    }    

?>
